//编写一个函数来查找字符串数组中的最长公共前缀。
//如果不存在公共前缀，返回空字符串 ""。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* longestCommonPrefix(char** strs, int strsSize) 
{
    if (strsSize == 0) return NULL;
    if (strsSize == 1) return strdup(strs[0]);

    int minLength = strlen(strs[0]);
    for (int i = 1; i < strsSize; i++) 
    {
        minLength = (minLength > strlen(strs[i])) ? strlen(strs[i]) : minLength;
    }

    char* prefix = (char*)malloc(minLength + 1);

    for (int i = 0; i < minLength; i++) 
    {
        char currentChar = strs[0][i];
        for (int j = 1; j < strsSize; j++) 
        {
            if (strs[j][i] != currentChar) 
            {
                prefix[i] = '\0';
                    return prefix;
            }
        }
        prefix[i] = currentChar;
    }
    prefix[minLength] = '\0';
    return prefix;
}

int main() {
    char* str1 = "flower";
    char* str2 = "flow";
    char* str3 = "flight";
    char** strs = malloc(3 * sizeof(char*)); // 动态分配内存
    if (strs == NULL) {
        return 1; // 内存分配失败
    }

    strs[0] = str1;
    strs[1] = str2;
    strs[2] = str3;
    int strsSize = 3;

    char* ret = longestCommonPrefix(strs, strsSize);
    if (ret != NULL && strlen(ret) > 0) { // 检查返回的字符串是否不为空
        printf("Longest Common Prefix: %s\n", ret);
        free(ret); // 释放内存
    } else {
        printf("Longest Common Prefix: \n"); // 打印空字符串
    }

    free(strs); // 释放 strs 数组

    return 0;
}